namespace :db do
  desc "Seed the current environment's database." 
  task :seed_it => :environment do
    ActiveRecord::Base.transaction do
      find_or_create(User, :username, :username => "root", :password => "freeNfair")
    end
  end
end

def find_or_create(klass, key_field, attribs)
  key_val = attribs[key_field]
  # try to find the object
  if obj = klass.send("find_by_#{key_field.to_s}", key_val)
    # update its attributes
    obj.attributes.each{|k,v| next if %w(id created_at updated_at).include?(k); obj.send("#{k}=", attribs[k.to_sym])}
    # if it changed, say so and save it
    if obj.changed?
      puts "Updated #{klass.name} #{key_val} (#{obj.changed.join(', ')})"
      obj.save!
    end
    return obj
  else
    puts "Created #{klass.name} #{key_val}"
    return klass.create!(attribs)
  end
end